package com.jsyxdl.conntroller;


import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.dto.PartUsageLink;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartDescribeLinkService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.user.service.ErpBomService;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.listener.handling.MaterialsBatchHandling;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigInteger;
import java.util.*;

@RestController
@RequestMapping("/rest/v1/synerp")
public class SynErpController {

    @Autowired
    ErpBomService erpBomService;
    @Autowired
    TyplmPartDescribeLinkService typlmPartDescribeLinkService;
    @Autowired
    TyplmPartService typlmPartService;
    @Autowired
    TyplmPartBomService typlmPartBomService;


    @PostMapping("/finishedProduct")
    public ResponseResult finishedProduct(@RequestBody Map<String,Object> map) throws IOException {
        String str= (String) map.get("json");
        if(str!=null){
            List<PartDetailsVO> partDetailsVOList=new ArrayList<>();
            JSONArray arr=JSONArray.parseArray(str);
            for(int i=0;i<arr.size();i++){
                BigInteger coid = arr.getJSONObject(i).getBigInteger("oid");
                String coType = arr.getJSONObject(i).getString("otype");
                String view = arr.getJSONObject(i).getString("view");
                String number = arr.getJSONObject(i).getString("number");

                //PartDetailsVO partDetails = typlmPartService.queryPartDetails(coid, coType);

                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(view);
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("N");
                expandBomTreeByFilterDTO.setFatherNumber(number);
                expandBomTreeByFilterDTO.setFatherOid(coid.toString());
                expandBomTreeByFilterDTO.setFatherOtype(coType);
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(false);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);

                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);
                List<String> checkErrorList=new ArrayList<>();
                List<String> erpErrorList=new ArrayList<>();
                List<String> erpTypeErrorList=new ArrayList<>();





                Map<String, Object> partMap = new HashMap<>();
                for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                    PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                    if (partMap.containsKey(partBomTree.getObjectNumber())) {
                        continue;
                    } else {
                        partMap.put(partBomTree.getObjectNumber(), partBomTree);
                    }
                    BigInteger oid = new BigInteger(partBomTree.getPartoid());
                    String otype = partBomTree.getPartotype();
                    PartDetailsVO addPartDetails = typlmPartService.queryPartDetails(oid, otype);

                    if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                        if("c/i".equals(partBomTree.getCheckInOrCheckOut())==false){
                            checkErrorList.add(partBomTree.getObjectNumber());
                        }
                        if("ERP不管控零部件".equals(partBomTree.getTypeName())){
                            continue;
                        }
                        if(partBomTree.getIsLeafNode()==false){
                            Map<String, List<String>> attrMap=addPartDetails.getIbaAttributeMap();
                            if(attrMap.containsKey("物料属性")){
                                List<String> attr=attrMap.get("物料属性");
                                if("1".equals(attr.get(0))){
                                    erpTypeErrorList.add(partBomTree.getObjectNumber());
                                }
                            }
                        }
                    }

                    partDetailsVOList.add(addPartDetails);

                }
                if(checkErrorList.size()>0 && checkErrorList.size()>0 && erpTypeErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList)+" BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList)
                                                                                           +" 不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
                }
                else{
                    if(checkErrorList.size()>0){
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList));
                    }
                    if(erpErrorList.size()>0){
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList));
                    }
                    if(erpTypeErrorList.size()>0){
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
                    }
                }


            }
            if(partDetailsVOList.size()>0){
                K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
                Map<String, Object> executionType = k3CloudHttpService.getExecutionType("PLBC0001X", "BOM保存");
                executionType.put("code","PLBC0001X");
                executionType.put("k3cloud","BOM保存");

                MaterialsBatchHandling materialsBatchHandling=new MaterialsBatchHandling();
                try {
                    JSONObject erpResult=materialsBatchHandling.productionCall("否", executionType, partDetailsVOList);
                    JSONObject Result = erpResult.getJSONObject("Result");
                    if (Result != null) {
                        JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                        if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                            ResponseResult.fail("-1", ResponseStatus.get("Errors").toString());
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return ResponseResult.success();
    }


}
